package cn.neo.hhsharding.datasource;


import cn.neo.hhsharding.config.ShardingProperties;
import cn.neo.hhsharding.engine.ShardingContext;
import cn.neo.hhsharding.engine.ShardingResult;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.LinkedHashMap;
import java.util.Map;

public class ShardingDataSource extends AbstractRoutingDataSource {

    public ShardingDataSource(ShardingProperties properties) {
        // 创建数据源
        Map<Object, Object> dataSourceMap = new LinkedHashMap<>();
        properties.getDatasources().forEach((key, value) -> {
            try {
                dataSourceMap.put(key, DruidDataSourceFactory.createDataSource(value));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        setTargetDataSources(dataSourceMap);
        setDefaultTargetDataSource(dataSourceMap.values().iterator().next());

    }

    @Override
    protected Object determineCurrentLookupKey() {
        ShardingResult shardingResult = ShardingContext.get();
        String key = null == shardingResult ? null : shardingResult.getTargetDataSourceName();
        System.out.println(" ===> determineCurrentLookupKey=" +key);
        return key;
    }
}
